import React, { useState } from 'react';
import { Table, Switch } from 'antd';
import type { ColumnsType } from 'antd/es/table';

interface DataType {
  key: string;
  sections: string;
  state: boolean;
}

const data: DataType[] = [
  {
    key: '1',
    sections: '摄像头1',
    state: false,
  },
  {
    key: '2',
    sections: '摄像头2',
    state: false,
  },
  {
    key: '3',
    sections: '摄像头3',
    state: false,
  }
];


function GreenhouseSituationMonitor() {
  const [mediaTracks, setMediaTracks] = useState<MediaStreamTrack[]>([]);
  const columns: ColumnsType<DataType> = [
    {
      title: '监控',
      dataIndex: 'sections',
      key: 'sections'
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (isChecked, record) => <Switch onChange={(isOpen) => onChange(isOpen, record)} />
    }
  ];

  const onChange = (isOpen: boolean, record) => {
    if (!isOpen) {
      mediaTracks.forEach(track => track.stop())
    } else {
      getLocalStream({
        audio: false,
        video: true,
      });
    }
   };

  const getLocalStream = async (constraints: MediaStreamConstraints) => {
    // 获取媒体流
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    setMediaTracks(stream.getTracks());
    playLocalStream(stream);
  };

  const playLocalStream = (stream: MediaStream) => {
    const videoEl = document.getElementById('localVideo') as HTMLVideoElement
    videoEl.srcObject = stream
  }

  return (
    <>
      <Table
        columns={columns}
        dataSource={data}
        pagination={false}
      />
      <div>
        <video id="localVideo" autoPlay playsInline muted />
      </div>
    </>
  );
}

export default GreenhouseSituationMonitor;
